import axios from 'axios'
import {ElNotification} from "element-plus";


axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: "api",
    // 超时
    timeout: 10000
})

// 创建请求拦截
service.interceptors.request.use(
    (config) => {
        // 如果开启 token 认证
        if (localStorage.getItem("wx_token")) {
            config.headers["Authorization"] = localStorage.getItem("wx_token"); // 请求头携带 token
        }
        return config;
    },
    (error) => {
        Promise.reject(error).then(r => {
            console.log(r)
        });
    }
);


service.interceptors.response.use(
    response => {
        if (response.data.code===-1){
            ElNotification.warning({
                customClass:'warn',
                duration: 3000,
                message: response.data.msg,
                offset: 100,
            })
            return Promise.reject(response);
        }
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            ElNotification.warning({
                customClass:'warn',
                duration: 3000,
                message: response.data.msg,
                offset: 100,
            })
            return Promise.reject(response);
        }
    },
error => {
    if (error.response.status===401){
        localStorage.removeItem("wx_token")
        ElNotification.warning({
            title: '授权异常',
            customClass:'warn',
            duration: 3000,
            message: error.response.data.msg,
            offset: 100,
        })
    }else if (error.response.status===502){
        localStorage.removeItem("wx_token")
        ElNotification.warning({
            title: '授权异常',
            customClass:'warn',
            duration: 3000,
            message: error.response.data.msg,
            offset: 100,
        })
        window.location.hash = '/'
    }else if (error.response.status===500){
        ElNotification.warning({
            customClass:'warn',
            duration: 3000,
            message: error.response.data.msg,
            offset: 100,
        })
    }
    return Promise.reject(error)
});

export default service
